using System;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.Uow;
using Volo.Abp.Domain.Services;
using Volo.Abp.EventBus.Distributed;
using Joy.Erp.BasicArchives.Core.Events;

namespace Joy.Erp.BasicArchives.ItemMasters
{
    public class BillOfMaterialsManager : DomainService
    {
        protected IBillOfMaterialsRepository BillOfMaterialsRepository => LazyServiceProvider.LazyGetRequiredService<IBillOfMaterialsRepository>();
        protected IDistributedEventBus DistributedEventBus => LazyServiceProvider.LazyGetRequiredService<IDistributedEventBus>();

        [UnitOfWork]
        public async Task<BillOfMaterials> CreateAsync(BillOfMaterials entity, bool autoSave = false, CancellationToken cancellationToken = default)
        {
            entity.SetId(GuidGenerator.Create());
            entity.TenantId = CurrentTenant.Id;

            await DistributedEventBus.PublishAsync(new EntityCreatingEto<BillOfMaterials>(entity), false);
            return await BillOfMaterialsRepository.InsertAsync(entity, autoSave, cancellationToken);
        }

        [UnitOfWork]
        public async Task<BillOfMaterials> UpdateAsync(BillOfMaterials entity, bool autoSave = false, CancellationToken cancellationToken = default)
        {
            await DistributedEventBus.PublishAsync(new EntityUpdatingEto<BillOfMaterials>(entity), false);
            return await BillOfMaterialsRepository.UpdateAsync(entity, autoSave, cancellationToken);
        }

        [UnitOfWork]
        public async Task DeleteAsync(Guid id, bool autoSave = false, CancellationToken cancellationToken = default)
        {
            var entity = await BillOfMaterialsRepository.GetAsync(id);

            await DistributedEventBus.PublishAsync(new EntityDeletingEto<BillOfMaterials>(entity), false);
            await BillOfMaterialsRepository.DeleteAsync(entity, autoSave, cancellationToken);
        }
    }
}